package top.guagua.service.impl;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.guagua.api.result.VisitorResult;
import top.guagua.api.srv.VisitService;
import top.guagua.core.cache.CacheEntity;
import top.guagua.core.cache.CacheType;
import top.guagua.core.cache.RedisClientTemplate;
import top.guagua.service.bean.Visitor;
import top.guagua.service.dao.VisitorDao;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class VisitServiceImpl implements VisitService {

    private Logger logger = LoggerFactory.getLogger(VisitServiceImpl.class);

    @Resource
    private VisitorDao visitorDao;

    @Resource
    private RedisClientTemplate<String,Object> redisClientTemplate;

    @Override
    public List<VisitorResult> saveVisitor(VisitorResult visitorResult) {
        logger.info(JSON.toJSONString(visitorResult));
        visitorDao.insert(visitorResult);
        List<Visitor> visitorByPage = visitorDao.findVisitorByPage(new Visitor(), 0, 10);
        List<VisitorResult> visitorResults = new ArrayList<>();
        for (Visitor v:visitorByPage) {
            VisitorResult r = new VisitorResult();
            r.setUri(v.getUri());
            r.setTime(v.getTime());
            r.setIp(v.getIp());
            visitorResults.add(r);
        }
        redisClientTemplate.put(new CacheEntity("",CacheType.VisitManager),visitorResults,10, TimeUnit.MINUTES);
        List<VisitorResult> results = (List<VisitorResult>)redisClientTemplate.get(new CacheEntity("", CacheType.VisitManager));
        return results;
    }
}
